package com.huaqin.customer.expansion;

import com.huaqin.customer.SenderInterface;
import com.huaqin.salestracker.SalesTrackerService;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class SMSSender implements SenderInterface{
	
	private static final String TAG = "SMSSender";
	private static final String SMS_SEND_ACTIOIN = "com.huaqin.salestracker.send.message"; //send success or not
	private static final String SMS_DELIVERED_ACTION = "com.huaqin.salestracker.delivery.message"; //contact receive or not
	private static final String PATTERN = "[*]?[0-9]{4,12}";
	
	private TelephonyManager mTelephoneManager;
	private Context mContext = null;

	public static final int GEMINI_SIM_1 = 0; //Math MessageManager.java SIMId
	public static final int GEMINI_SIM_2 = 1;
	public static final int GEMINI_SIM = 2;
	
	private BroadcastReceiver mSMSSenderLister = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
		   try {
			   String actionName = intent.getAction(); 
			   int resultCode = getResultCode();
			   
			   Log.v(TAG, "onReceive >> actionName:[" + actionName + "] resultCode:[" + resultCode + "]");
			   
			   Intent sendIntent = new Intent();
			   
			   if (actionName.equals(SMS_SEND_ACTIOIN)) { 
				   sendIntent.setAction(SalesTrackerService.STCMD_SEND_RESULT);
				   
				   switch (resultCode) {  
					   case Activity.RESULT_OK: 
						   
						   Log.d(TAG,"[Send]SMS Send:Successed!");
						   sendIntent.putExtra(SalesTrackerService.KEY_RESULT, true);
						   
						   break;  
					   
					   case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
					   case SmsManager.RESULT_ERROR_NO_SERVICE:  
					   case SmsManager.RESULT_ERROR_NULL_PDU:  
					   case SmsManager.RESULT_ERROR_RADIO_OFF:
						   
						   Log.e(TAG,"[Send]SMS Send:Failded!");
						   sendIntent.putExtra(SalesTrackerService.KEY_RESULT, false);
						   
						   break;  
						 
						default:
							break;
				   } 
				   
				   context.sendBroadcast(sendIntent);
				   
			   } else if (actionName.equals(SMS_DELIVERED_ACTION)) {
				   
				   switch (resultCode) {  
					   case Activity.RESULT_OK:  
						   Log.d(TAG,"[Delivery]SMS Delivery:Successed!");  
						   break;

					   case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
						   Log.d(TAG,"[Delivery]SMS Delivery:RESULT_ERROR_GENERIC_FAILURE!");  
						   break;

					   case SmsManager.RESULT_ERROR_NO_SERVICE:  
						   Log.d(TAG,"[Delivery]SMS Delivery:RESULT_ERROR_NO_SERVICE!");  
						   break;

					   case SmsManager.RESULT_ERROR_NULL_PDU:  
						   Log.d(TAG,"[Delivery]SMS Delivery:RESULT_ERROR_NULL_PDU!");  
						   break;

					   case SmsManager.RESULT_ERROR_RADIO_OFF:  
						   Log.d(TAG,"[Delivery]SMS Delivery:RESULT_ERROR_RADIO_OFF!");  
						   break;  
				   }

			   }
			   
			   UnRegisterReceiver();
		   }
		   catch (Exception e) {
			    e.getStackTrace();
		   }
		}
	};
	
	public SMSSender(){
	    try {
	        mContext = SalesTrackerService.mContext;
	        mTelephoneManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "SMSSender construction error");
        }
	}
	
	public int getSMSSendMode(){
		return SalesTrackerService.mSMSSendMode;
	}
	
	private void RegisterReceiver(){
		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(SMS_SEND_ACTIOIN);
		commandFilter.addAction(SMS_DELIVERED_ACTION);
		mContext.registerReceiver(mSMSSenderLister, commandFilter);
	}
	
	private void UnRegisterReceiver(){
		mContext.unregisterReceiver(mSMSSenderLister);
	}

	@Override
	public boolean checkAddress(String address) {
		// TODO Auto-generated method stub
		return address.matches(PATTERN);
	}
	
	/**
	 * @author nixionglin
	 */
	@Override
	public boolean send(String address, String message) {
		// TODO Auto-generated method stub
		
		Log.i("SMSSender", "Send: address:[" + address + "]message:[" + message + "]");

		if(address == null || message == null){
			return false;
		}
		
		boolean result = false;
		int simId = getUsingSimId();
		if(CheckSimState(simId)){
		    PendingIntent psentIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(SMS_SEND_ACTIOIN), PendingIntent.FLAG_CANCEL_CURRENT);
	        PendingIntent pdeliveryIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(SMS_DELIVERED_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
/*
	        if(SalesTrackerService.MTK_GEMINI_SUPPORT == true) {                    
	            GeminiSmsManager.sendTextMessageGemini(address, null, message, simId, psentIntent, pdeliveryIntent);
	        }
	        else {
	            SmsManager smsManager = SmsManager.getDefault();
	            smsManager.sendTextMessage(address, null, message, psentIntent, pdeliveryIntent);
	        }
*/
	        result = true;
	        
	        RegisterReceiver();
		}

		return result;
	}

	/**
	* 返回移动终端
	* 
	* SIM_STATE_ABSENT SIM卡未找到
	* SIM_STATE_NETWORK_LOCKED SIM卡网络被锁定，需要Network PIN解锁
	* SIM_STATE_PIN_REQUIRED SIM卡PIN被锁定，需要User PIN解锁
	* SIM_STATE_PUK_REQUIRED SIM卡PUK被锁定，需要User PUK解锁
	* SIM_STATE_READY SIM卡可用
	* SIM_STATE_UNKNOWN SIM卡未知
	*/
	public int getSIMState(){
		
		return 0;
	}

	/**
	 * @author nixionglin
	 * @return 0 - SIM1, 1 - SIM2, 2 SIM1/SIM2
	 */
	private int getUsingSimId() {
		//MTK method
/*		if (SalesTrackerService.MTK_GEMINI_SUPPORT)
		{
			if(SalesTrackerService.mSMSSendMode == GEMINI_SIM){
				if (mTelephoneManager.hasIccCardGemini(GEMINI_SIM_1)){
					return GEMINI_SIM_1;
				}	
				else if (mTelephoneManager.hasIccCardGemini(GEMINI_SIM_2)) {
					return GEMINI_SIM_2;
				}
			}
			else{
				//check the set sim can use
				if (mTelephoneManager.hasIccCardGemini(SalesTrackerService.mSMSSendMode)){
					return SalesTrackerService.mSMSSendMode;
				}
			}
		}
*/
		return GEMINI_SIM_1; //default
	}
	
	private boolean CheckSimState(int simId) {
/*
		if (SalesTrackerService.MTK_GEMINI_SUPPORT) {
			return ((mTelephoneManager.hasIccCardGemini(GEMINI_SIM_1))||(mTelephoneManager.hasIccCardGemini(GEMINI_SIM_2)));
		}
		else {
			return (mTelephoneManager.hasIccCardGemini(GEMINI_SIM_1));		
		}
*/
		return true;
	}

}
